const fs = require('fs');

// 读取文本文件并解析为JSON
function parseQuestions(filePath) {
  const content = fs.readFileSync(filePath, 'utf-8');
  const lines = content.split('\n').filter(line => line.trim() !== '');

  const questions = [];
  let current = -1

  for (const line of lines) {
    const text = line.replace(/\s/g, '').replace(/\r/g, '');

    const isTitle = /^\d+\.(.+)/.test(text);
    if (isTitle) {
      let option = []
      current += 1
      let title = text.replace(/^\d+\./, '') // 去掉开头的序号和点
      let answer = -1

      if (/(A|B|C|D)/.test(title)) {
        const answerABCDMatch = title.match(/（(A|B|C|D)）/);
        answer = answerABCDMatch ? 'ABCD'.indexOf(answerABCDMatch[1]) : null;
        title = title.replace(/（(A|B|C|D)）/, '（）')
      } else if (/（(错误|正确)）/.test(title)) {
        option = ['正确', '错误']
        const answerYesNoMatch = title.match(/（(错误|正确)）/);
        answer = answerYesNoMatch ? ['错误', '正确'].findIndex(a => a === answerYesNoMatch[1]) : null;
        title = title.replace(/（(错误|正确)）/, '');
      }

      questions.push({
        "title": title,
        "type": "单选",
        "option": option,
        "answer": answer,
        "questionBankId": '682fc05c09664cca981534f2',
      })
    }

    const isOption = /^[A-Za-z]\.?(.+)/.test(text)
    if (isOption) {
      const match = text.match(/^[A-Za-z]\.?(.+)/);
      questions[current].option.push(match ? match[1] : text)// 如果匹配失败，返回原字符串
    }

  }

  return questions;
}

// 执行转换
try {
  const questions = parseQuestions('input.txt');
  console.log(`解析到的题目数量: ${questions.length}`);

  fs.writeFileSync('output.json', questions.map(o => JSON.stringify(o)).join('\n'), 'utf-8');
} catch (err) {
  console.error('处理失败:', err);
}